/**
 * create by xiangyang.cheng1 on 2016.07.19
 */
package com.dragon.cloud.zconf.util;

import com.dragon.cloud.zconf.client.ZConfNodeImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
    private static final String ENCODE = "UTF-8";

    /**
     * 保存配置到本地文件
     * 
     * @param path
     *            full path
     * @param value
     *            如果value == null, 则会存储为空字符串 ""
     */
    public static void saveToLocalFileCache(String path, String value) {
        FileOutputStream out = null;
        PrintWriter writer = null;
        String filePath = getLocalFilePath(path);
        try {
            File file = new File(filePath);
            if (file.exists()) {
                if (file.isDirectory()) {

                    org.apache.commons.io.FileUtils.deleteDirectory(file);
                    file.createNewFile();
                }

            } else {
                try {
                    File dir = new File(getLocalFilePath(path).substring(0, getLocalFilePath(path).lastIndexOf("/")));

                    if (dir.exists() && !dir.isDirectory()) {
                        dir.delete();
                    }
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    file.createNewFile();
                } catch (RuntimeException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            out = new FileOutputStream(file);
            BufferedOutputStream stream = new BufferedOutputStream(out);
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, ENCODE)));
            writer.write((value == null) ? "" : value);
            writer.flush();
        } catch (IOException e) {
            logger.error(
                new StringBuilder().append("save to localFile falied, filePath= ").append(filePath).toString(),
                e);
        } finally {
            if (writer != null) {
                writer.close();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 从配置文件取配置
     * 
     * @param path
     *            full path
     * @return empty value("") if read file failed
     */
    public static String loadFromLocalFileCache(String path) {
        String filePath = getLocalFilePath(path);
        String value = ZConfNodeImpl.NULL_VALUE;
        File file = new File(filePath);
        if (!(file.exists())) {
            logger.error("LocalFile is not exist,filePath:" + filePath);
            return value;
        }
        FileInputStream in = null;
        StringBuilder sb = new StringBuilder(512);

        try {
            in = new FileInputStream(file);
            byte[] data = new byte[8192];
            int n = -1;
            while ((n = in.read(data)) != -1) {
                sb.append(new String(data, 0, n, ENCODE));
            }
            value = sb.toString();
        } catch (IOException e) {
            logger.error(new StringBuilder().append("load localFile failed, filePath= ").append(filePath).toString(),
                e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return value;
    }

    private static String getLocalFilePath(String path) {
        return new StringBuilder().append(ZConfConstant.CONFIG_STORE_FILE_PATH)
            .append(ZConfNodeUtil.StringFilter(path)).toString();
    }
}
